package org.jgs1904.controller;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.jgs1904.bean.Pager;
import org.jgs1904.entity.Post;
import org.jgs1904.entity.User;
import org.jgs1904.service.PostService;
import org.jgs1904.service.impl.PostServiceImpl;
import org.jgs1904.util.FileUploadUtil;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;

/**
 * 帖子控制器
 * 
 * @author junki
 * @date 2020年3月26日
 */
@WebServlet("/post")
public class PostController extends DispatcherController {

	private static final long serialVersionUID = 1L;

	private PostService postService = new PostServiceImpl();

	/**
	 * 分页查询所有帖子
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public void page(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		// 获取分页参数
		String currentPageStr = request.getParameter("currentPage");
		String pageSizeStr = request.getParameter("pageSize");

		Long currentPage = 1L;
		Long pageSize = 10L;
		Long pageNumShowLength = 6L;

		if (StringUtils.isNotBlank(currentPageStr)) {
			currentPage = Long.valueOf(currentPageStr);
		}

		if (StringUtils.isNotBlank(pageSizeStr)) {
			pageSize = Long.valueOf(pageSizeStr);
		}

		// 调用service方法
		Pager<Post> pager = null;
		try {
			pager = postService.getPage(currentPage, pageSize, pageNumShowLength, request.getParameterMap());
		} catch (SQLException e) {
			e.printStackTrace();
		}

		request.setAttribute("post", request.getParameterMap());
		request.setAttribute("pager", pager);

		request.getRequestDispatcher("/post/list.jsp").forward(request, response);
	}

	/**
	 * 查询所有帖子
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public void list(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		List<Post> postList = null;
		try {
			postList = postService.getList();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		request.setAttribute("postList", postList);

		request.getRequestDispatcher("/post/list.jsp").forward(request, response);
	}

	/**
	 * 发帖方法
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public void add(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		User onlineUser = (User) request.getSession().getAttribute("onlineUser");

		Post post = new Post();
		try {
			BeanUtils.populate(post, FileUploadUtil.upload(request));
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 验证内容是否为空
		// null、" " 、""
		if (StringUtils.isAnyBlank(post.getTitle(), post.getContent())) {
			request.setAttribute("message", "标题和内容不能为空！");
			request.setAttribute("post", post);
			request.getRequestDispatcher("/post/send.jsp").forward(request, response);
			return;
		}

		post.setUser_id(onlineUser.getId());
		post.setCreate_time(new Date());

		Post result = null;
		try {
			result = postService.add(post);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		if (result == null) {
			request.setAttribute("message", "发帖失败！请重试！");
			request.setAttribute("post", post);
			request.getRequestDispatcher("/post/send.jsp").forward(request, response);
		} else {
			response.sendRedirect(request.getContextPath() + "/post?method=page");
		}
	}

	/**
	 * 获取一条数据
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public void get(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		Long id = Long.valueOf(request.getParameter("id"));

		Post post = null;
		try {
			post = postService.getOneById(id);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		request.setAttribute("post", post);

		request.getRequestDispatcher("/post/detail.jsp").forward(request, response);
	}
	
	/**
	 * 	导出excel表格
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		List<Post> list = null;
		try {
			list = postService.getList();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		if (list != null) {
			Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("所有帖子", "帖子"), Post.class, list);
			response.setContentType("application/vnd.ms-excel");
			String filename = new String("所有帖子.xls".getBytes("UTF-8"), "ISO8859-1");
			response.addHeader("Content-Disposition", "attachment; filename=" + filename);
			workbook.write(response.getOutputStream());
		}
		
	}

	
	/**
	 * 	导入excel表格
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		Map<String, String[]> requestParams = FileUploadUtil.upload(request);
		
		String path = requestParams.get("excel")[0];
		
		String realPath = request.getServletContext().getRealPath(path);
		
		ImportParams params = new ImportParams();
		params.setTitleRows(1);
		params.setHeadRows(1);
		List<Post> list = ExcelImportUtil.importExcel(new File(realPath), Post.class, params);
		
		try {
			postService.addAll(list);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		response.sendRedirect(request.getContextPath() + "/post?method=page");
	}
}
